<!-- created by zyt -->
<!-- updated by ljx --2022.01.05 --><!-- 增加partition参数，设置一行搜索项的个数 -->
<!-- updated by ljx --2022.01.12 --><!-- 搜索项展开【更多】和【收起】样式调整 -->
<template>
  <div class="cac-search-form">
    <a-form :form="form" @submit="handleSubmit" @submit.native.prevent @keyup.enter.native="handleSubmit">
      <a-row :gutter="24">
        <span
          v-for="(item, index) in dataSource"
          v-show="index < partition - 1 || (index >= (partition - 1) && collapsed)"
          :key="item.fieldName"
          :item-options="item"
        >
          <a-col :span="24 / partition">
            <a-form-item :label="item.labelText">
              <a-input
                v-if="item.type === 'text'"
                v-model="form[item.fieldName]"
                allow-clear
                :placeholder="item.hasOwnProperty('placeholder')?item.placeholder:'请输入'"
              />
              <a-input-number
                v-if="item.type === 'number'"
                v-model="form[item.fieldName]"
                allow-clear
                style="width: 100%"
                :min="item.hasOwnProperty('min')?item.min:0"
                :max="item.hasOwnProperty('max')?item.max:2147483647"
                :placeholder="item.hasOwnProperty('placeholder')?item.placeholder:'请输入'"
              />
              <a-select
                v-else-if="item.type === 'select'"
                v-model="form[item.fieldName]"
                allow-clear
                :label-in-value="item.hasOwnProperty('labelInValue')?item.labelInValue : false "
                :filter-option="item.search?filterOption:null"
                :placeholder="item.hasOwnProperty('placeholder')?item.placeholder:'请选择'"
              >
                <a-select-option
                  v-for="(optionitem, optionindex) in item.options"
                  :key="optionindex"
                  :value="optionitem.hasOwnProperty('key')? optionitem.key : optionitem.value"
                > {{ optionitem.label }} </a-select-option>
                <a-select-option key="asdfghjkl" value="">全部查询</a-select-option>

              </a-select>
              <a-cascader
                v-else-if="item.type === 'cascader'"
                v-model="form[item.fieldName]"
                change-on-select
                :options="item.options"
                expand-trigger="hover"
                :display-render="({ labels })=>{return labels[labels.length - 1] }"
                :placeholder="item.hasOwnProperty('placeholder')?item.placeholder:'请选择'"
                :field-names="item.hasOwnProperty('fieldNames')?item.fieldNames:{ label: 'label', value: 'value', children: 'children' }"
              />
              <a-date-picker
                v-else-if="item.type === 'datetime'"
                v-model="form[item.fieldName]"
                :show-time="showtimeformat(item)"
                :value-format="item.format?item.format:'YYYY-MM-DD HH:mm'"
                allow-clear
                style="width: 100%"
                :placeholder="item.hasOwnProperty('placeholder')?item.placeholder:'请选择日期'"
              />
              <a-time-picker
                v-else-if="item.type === 'time'"
                v-model="form[item.fieldName]"
                :show-time="showtimeformat(item)"
                :format="item.format?item.format:'HH:mm'"
                allow-clear
                style="width: 100%"
                :placeholder="item.hasOwnProperty('placeholder')?item.placeholder:'请选择时间'"
              />
              <a-range-picker
                v-else-if="item.type === 'datetimeRange'"
                v-model="form[item.fieldName]"
                :show-time="showtimeformat(item)"
                :value-format="item.format?item.format:'YYYY-MM-DD'"
                allow-clear
                style="width: 100%"
                :placeholder="item.hasOwnProperty('placeholder')?item.placeholder:['开始日期','结束日期']"
              />
              <basictypesearch
                v-else-if="item.type === 'dictionary'"
                v-model="form[item.fieldName]"
                :pcode="item.pcode"
                :typeid="item.typeid"
                :placeholder="item.hasOwnProperty('placeholder')?item.placeholder:'请选择'"
              />
              <slot v-else-if="item.type === 'other'" :form="form" :name="item.fieldName" />
            </a-form-item>
          </a-col>
        </span>
        <!-- <a-col :span="inlineRowSpan" :style="{ display: 'block', height: '100%', textAlign: 'right' }" :class="collapsed ? 'inlineBtnRow' : null"> -->
        <a-col class="inlineBtnRow" :span="inlineRowSpan">
          <a-button type="primary" @click="handleSubmit">
            查询
          </a-button>
          <a-button style="margin-left: 8px" @click="resetSearchForm">
            清空
          </a-button>
          <template v-if="showCollapsedText">
            <a v-if="!collapsed" :style="{ marginLeft: '8px', fontSize: '12px' }" @click="togglecollapsed">
              更多
              <!-- <a-icon :type="collapsed ? 'up' : 'down'" /> -->
              <a-icon type="down" />
            </a>
            <a v-else :style="{ marginLeft: '8px', fontSize: '12px' }" @click="togglecollapsed">
              收起
              <a-icon type="up" />
            </a>
          </template>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script>
import basictypesearch from '../basictypesearch.vue'
export default {
  components: {
    basictypesearch
  },
  props: {
    expand: {
      type: Boolean
    },
    dataSource: { // 搜索配置项
      type: Array,
      default: function() {
        return []
      }
    },
    partition: { // 一行搜索项的个数，默认为4
      type: Number,
      default: 4
    }
  },
  data() {
    return {
      form: {},
      collapsed: false // 是否展开，默认否
    }
  },
  computed: {
    showCollapsedText() {
      // 显示【展开/收缩】的判定：若搜索项个数>this.partition - 1返回true；(代表无法显示全)
      return this.dataSource.length > (this.partition - 1)
    },
    inlineRowSpan() {
      // 根据this.collapsed状态，计算【查询】、【清空】部分所占的span数；
      return !this.collapsed ? 24 / this.partition : 24 / this.partition * (this.partition - this.dataSource.length % this.partition)
    }
  },
  watch: {
    dataSource: {
      immediate: true,
      handler: function() {
        this.initalForm()
        // 搜索项的个数小于partition-1时默认"展开"状态，便于inlineRowSpan函数中，采用"展开"条件下的【查询】部分宽度计算规则
        if (this.dataSource.length < this.partition) {
          this.togglecollapsed()
        }
        // console.log('AdvancedSearch--this.form', this.form)
      }
    },
    expand: {
      handler: function() {
        this.collapsed = this.expand
      }
    }
  },
  methods: {
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    showtimeformat(item) {
      let returndata = false
      if (item.hasOwnProperty('format')) {
        const showtime = item.format.split(' ')[1]
        if (showtime !== undefined) {
          returndata = { format: showtime }
        }
      } else if (item.type === 'datetime' && !item.hasOwnProperty('format')) {
        returndata = true
      }
      return returndata
    },
    initalForm() {
      this.dataSource.forEach(element => {
        if (element.type === 'datetimeRange' || element.type === 'cascader') {
          this.$set(this.form, element.fieldName, [])
        } else {
          this.$set(this.form, element.fieldName, '')
        }
      })
    },
    togglecollapsed() {
      this.collapsed = !this.collapsed
    },
    handleSubmit() {
      const reqdata = {}
      this.dataSource.forEach(element => {
        if (this.form[element.fieldName] !== '') {
          if (element.type === 'datetimeRange') {
            if (this.form[element.fieldName].length !== 0) {
              if (element.rangeformat === 'date') {
                reqdata[element.fieldName + 'Begin'] = this.form[element.fieldName][0]
                reqdata[element.fieldName + 'End'] = this.form[element.fieldName][1]
              } else {
                reqdata[element.fieldName + 'Begin'] = this.form[element.fieldName][0] + ' 00:00'
                reqdata[element.fieldName + 'End'] = this.form[element.fieldName][1] + ' 23:59'
              }
            }
          } else if (element.type === 'cascader') {
            if (this.form[element.fieldName].length !== 0) {
              reqdata[element.fieldName] = this.form[element.fieldName]
            }
          } else if (element.type === 'dictionary') {
            if (element.dictionarytype ? (element.dictionarytype === 'array') : false) {
              reqdata[element.fieldName] = []
              reqdata[element.fieldName].push(this.form[element.fieldName])
            } else if (element.dictionarytype ? (element.dictionarytype === 'code') : false) {
              reqdata[element.fieldName] = this.form[element.fieldName].code
            } else {
              reqdata[element.fieldName] = this.form[element.fieldName]
            }
          } else {
            reqdata[element.fieldName] = this.form[element.fieldName]
          }
        }
      })
      this.$emit('change', reqdata)
    },
    resetSearchForm() {
      // 重置整个查询表单
      console.log('reset')
      this.initalForm()
      this.handleSubmit()
    }
  }
}
</script>

<style scoped>
.inlineBtnRow {
  display: block;
  margin-top: 24px;
  text-align: right
}
</style>
